package com.ruoyi.web.controller;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.OperatorType;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.student.domain.vo.IZHICHENGAuthVo;
import com.ruoyi.system.service.ISysUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RestController
public class AuthController extends BaseController {

    String key = "(@<rhnPaUYKC_k770*DuWwYQ_#Zc#8c(2rB?kae)rN)>K7qy)awCjxp$L653Mf$2";

    //签发地址
    String iss = "https://uis.fdzcxy.edu.cn/cas";

    //验证地址
    String aud = "https://student-work,fdzcxy.edu.cn/auth";


    @Resource
    private SysLoginService loginService;

    @Resource
    private ISysUserService sysUserService;

    /**
     * cas 认证方法
     *
     * @param vo
     * @return
     */
    //@Log(title = "用户登入", operatorType = OperatorType.MANAGE, businessType = BusinessType.OTHER)
    @PostMapping("/cas/auth")
    public AjaxResult auth(@RequestBody IZHICHENGAuthVo vo) {
        //ticket验签
        String ticket = java.net.URLDecoder.decode(vo.getTicket());
        AjaxResult ajax = AjaxResult.success();
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(key.getBytes()).parseClaimsJws(ticket).getBody();
        } catch (Exception e) {
            AjaxResult errorAjax = AjaxResult.success("解析ticket出错：" + e.getMessage());
            errorAjax.put("isUser", false);
            return errorAjax;
        }
        String code = claims.getSubject();
        if (!code.equals(vo.getCode())) {
            AjaxResult errorAjax = AjaxResult.success("前后端校验不一致");
            errorAjax.put("isUser", false);
            return errorAjax;
        }
        //判断当前用户存在，是否启用
        SysUser user = sysUserService.selectUserByUserName(vo.getCode());
        if (ObjectUtil.isEmpty(user)) {
            AjaxResult errorAjax = AjaxResult.success("您的账号没有访问本系统的权限");
            errorAjax.put("isUser", false);
            return errorAjax;
        }
        if (user.getStatus().equals("1")) {
            //账号已被禁止登入
            AjaxResult errorAjax = AjaxResult.success("您的账号没有访问本系统的权限");
            errorAjax.put("isUser", false);
            return errorAjax;
        }
        String token = loginService.login(user);
        ajax.put(Constants.TOKEN, token);
        ajax.put("isUser", true);
        return ajax;
    }
}
